<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="login-title">登录</div>
      <el-form ref="loginForm" :model="loginForm" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <div class="button-container">
            <el-button type="primary" @click="submitForm">登录</el-button>
            <el-button type="text" @click="goToRegister">注册</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>

import axios from "@/Api/axiosInterceptor.ts";
import {headerConfig} from "@/Api/HeaderConfig.ts";

export default {
  data() {
      return {
          loginForm: {
              username: '',
              password: ''
          },
          rules: {
              username: [
                  {required: true, message: '请输入用户名', trigger: 'blur'}
              ],
              password: [
                  {required: true, message: '请输入密码', trigger: 'blur'},
                  {min: 6, message: '密码长度不能小于6位', trigger: 'blur'}
              ]
          }
      };
  },
    methods: {
        async submitForm() {
            this.$refs.loginForm.validate(async (valid) => {
                if (valid) {
                    axios.post('/users/login', this.loginForm, headerConfig).then((response) => {
                        localStorage.setItem('user_token', response.data.token);
                        this.$router.push('/mainwindow');
                    }).catch((err)=> {
                        console.log(err);
                    })
                } else {
                    console.log('表单验证失败!');
                    return false;
                }
            });
        },
        goToRegister() {
            this.$router.push('/register');
        }
    }
};
</script>

<style scoped>
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100vw;
    height: 100vh;
    background-image: url("../assets/img.png");
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}

.login-card {
    width: 400px;
    padding: 20px;
    border-radius: 10px;
}

.login-title {
    font-size: 24px;
    margin-bottom: 20px;
    text-align: center;
}

.button-container {
    width: 100%;
    display: flex;
    justify-content: center;
}
</style>